package com.lgl.service.impl;

import com.lgl.entity.ResponseResult;
import com.lgl.service.EmailService;
import com.lgl.utils.CodeUtil;
import com.lgl.utils.EmailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmailServiceImpl implements EmailService {
    @Autowired
    private EmailUtils emailUtils;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // Spring官方提供的集成邮件服务的实现类，目前是Java后端发送邮件和集成邮件服务的主流工具。
    @Resource
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String fromEmail;

    @Override
    public ResponseResult sendEmail(String email) {
        String code = CodeUtil.createCode(6).toLowerCase();
        String subject = "验证码";
        // 使用Map作为数据模型，定义属性和值
        Map model = new HashMap();
        model.put("code",code);
        emailUtils.sendTemplateMail(email, subject, "template.ftl",model);
        stringRedisTemplate.opsForValue().set("email:code:" + email, code, 60, TimeUnit.SECONDS);
        return ResponseResult.okResult();
    }
}
